<template>
  <!-- 质量工匠之星 -->
  <base-breadcrumb>
    <searchData :searchData="searchOptions" @search="search" />
    <div class="page-body">
      <a-card :bordered="false">
        <!-- <title-name :title="$route.meta.title" /> -->
        <!-- 分类面板 -->
        <a-spin :spinning="spinning">
          <a-tabs v-model="active" :animated="false">
            <a-tab-pane v-for="item in tabList" :key="item.id" :tab="item.name">
              <list-table
                v-if="active === -1"
                :ref="'table_' + item.id"
                size="default"
                rowKey="id"
                :startIndex="0"
                :columns="columns[2]"
                :request="loadData"
                :isShowCountBar="false"
                @select-click="expandedRowSelection"
                :selectConfig="{ use: true, type: 'checkbox' }"
                :exportConfig="{ use: true, select: '质量工匠之星汇总', all: '质量工匠之星汇总' }"
              >
                <template slot="suffix">
                  <!-- 统计汇总 -->
                  <AuditSummary :api="api" :ref="'auditSummary_' + item.id" apiName="AllSummary" title=" " :form="{ ...queryParam, starType: 1 }" :countList="countList[3]" style="margin-top: 12px" />
                </template>
                <ListTable
                  slot="expandedRowRender"
                  slot-scope="record"
                  :ref="'table_' + item.id"
                  size="default"
                  rowKey="id"
                  :columns="[
                    { dataIndex: 'projectName', title: '项目名称' },
                    { dataIndex: 'cardNum', title: '累计发卡数量' },
                    { dataIndex: 'weekStarNum', title: '周质量工匠之星数量' },
                    { dataIndex: 'monthStarNum', title: '月质量工匠之星数量' },
                    { dataIndex: 'rewardTotal', title: '累计奖励金额' }
                  ]"
                  :request="(e) => getBranchProjectSummary(e, record.branchComId)"
                  :isShowCountBar="false"
                />
              </list-table>
              <list-table
                v-else
                :ref="'table_' + item.id"
                size="default"
                rowKey="id"
                :columns="columns[columnIndex > 1 ? columnIndex - 1 : columnIndex]"
                :request="loadData"
                :isShowCountBar="false"
                :startIndex="0"
                @select-click="rowSelection"
                :selectConfig="{ use: true, type: 'checkbox' }"
                :exportConfig="{ use: true, select: exportTitle, all: exportTitle }"
              >
                <template slot="suffix">
                  <!-- 统计汇总 -->
                  <AuditSummary
                    :ref="'auditSummary_' + item.id"
                    apiName="summary"
                    :form="{ ...queryParam, starType: 1, qualityStarTypeId: active }"
                    :api="api"
                    title=" "
                    :countList="countList[columnIndex]"
                    style="margin-top: 12px"
                  />
                </template>
                <template slot="actions" slot-scope="text, record">
                  <more-button>
                    <a class="base-btn" @click="handleOperate(record)">查看</a>
                    <a
                      class="base-btn"
                      v-if="hideBuquBtn()"
                      @click="
                        form = record
                        visible = true
                      "
                      >推送至质量月报</a
                    >
                  </more-button>
                </template>
              </list-table>
            </a-tab-pane>
          </a-tabs>
        </a-spin>
      </a-card>
    </div>
    <!-- 选择推送至质量月报 -->
    <dialog-Form
      ref="dialogForm"
      headerTitle="选择推送至质量月报"
      editModel="E"
      :visible.sync="visible"
      :form="form"
      :formList="[
        {
          keyName: 'employeeName',
          label: '姓名',
          disabled: true,
          span: 12,
          type: 'BaseInput'
        },
        {
          keyName: 'subcontractorName',
          label: '分包单位',
          disabled: true,
          span: 12,
          type: 'BaseInput'
        }
      ]"
      :width="1000"
      @confirm="handlePush"
    >
      <!-- 表格 -->
      <b-table
        v-if="visible"
        slot="formFooter"
        ref="tableDialogForm"
        :pageKeys="['pageNum', 'pageSize', 'total']"
        :columns="columnsTwo"
        :request="loadDataTwo"
        :showPage="false"
        :selectConfig="{ use: true, type: 'checkbox', rowKey: 'id' }"
      >
        <!-- 照片 -->
        <template slot="fileArrays" slot-scope="text, record">
          <l-table v-if="record.fileArrays && record.fileArrays.length > 0" uploadType="image" :disabled="true" :editModel="0" :uploadArrys.sync="record.fileArrays" multiple></l-table>
          <span v-else>无</span>
        </template>
      </b-table></dialog-Form
    >
  </base-breadcrumb>
</template>

<script>
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目名称
import OrgTreeSelect from '@/components/OrgTreeSelect'
import SelectSubcontractor from '@/components/Select/SelectSubcontractor' // 分包商
import { star, typesLabel } from '@/api/quality/quality' // api
import AuditSummary from '@/views/quality/components/AuditSummary' // 统计汇总
import { Empty } from 'ant-design-vue'
import SelectProjectStatus from '@/views/quality/components/SelectProjectStatus' // 项目状态
import MoreButton from '@/components/MoreButton'
import DialogForm from '@/components/DialogForm' // 选择推送至质量月报
import { selectOption } from '@/api/material/goods/goods'

export default {
  name: 'a' + Date.now(),
  components: {
    AEmpty: Empty,
    AuditSummary,
    MoreButton,
    DialogForm
  },
  data() {
    return {
      form: {}, // 选中行表单
      visible: false, // 选择推送至质量月报控件
      loadDataTwo: () => {
        return star.records({ month: 1, starType: 1, employeeId: this.form.employeeId, qualityStarTypeId: this.active }).then((res) => {
          return res
        })
      },
      spinning: false, // tab加载控件
      expandedRowKeys: [],
      active: 0, // 当前选中面板值
      tabList: [
        {
          id: -1,
          name: '质量工匠之星汇总'
        }
      ],
      countList: [
        [
          {
            title: '发卡总数：',
            value: 'total'
          },
          {
            key: 'select',
            title: '已选择：',
            value: 0
          },
          {
            title: '今日发卡数：',
            value: 'todayNum'
          },
          {
            title: '昨日发卡数：',
            value: 'yesterdayNum'
          },
          {
            title: '本周发卡数：',
            value: 'thisWeekNum'
          },
          {
            title: '本月发卡数：',
            value: 'thisMonthNum'
          }
        ],
        [
          {
            title: '月质量工匠之星总数：',
            value: 'total'
          },
          {
            key: 'select',
            title: '已选择：',
            value: 0
          },
          {
            title: '今日数量：',
            value: 'todayNum'
          },
          {
            title: '昨日数量：',
            value: 'yesterdayNum'
          },
          {
            title: '本周数量：',
            value: 'thisWeekNum'
          },
          {
            title: '本月数量：',
            value: 'thisMonthNum'
          }
        ],
        [
          {
            title: '周质量工匠之星总数：',
            value: 'total'
          },
          {
            key: 'select',
            title: '已选择：',
            value: 0
          },
          {
            title: '今日数量：',
            value: 'todayNum'
          },
          {
            title: '昨日数量：',
            value: 'yesterdayNum'
          },
          {
            title: '本周数量：',
            value: 'thisWeekNum'
          },
          {
            title: '本月数量：',
            value: 'thisMonthNum'
          }
        ],
        [
          // {
          //   title: '质量工匠之星总数：',
          //   value: 'total'
          // },
          {
            title: '项目总数：',
            needUnit: true,
            value: 'projectAllTotal'
          },
          {
            key: 'select',
            title: '已选择：',
            value: 0
          },
          {
            title: '开展项目数：',
            needUnit: true,
            value: 'developProjectAllNum'
          },
          {
            title: '推广率：',
            value: 'spread',
            needUnit: true,
            unit: '%'
          },
          {
            title: '累计发卡数量：',
            needUnit: true,
            value: 'cardAllNum'
          },
          {
            title: '周质量之星数量：',
            needUnit: true,
            value: 'weekStarAllNum'
          },
          {
            title: '月质量之星数量：',
            needUnit: true,
            value: 'monthStarAllNum'
          },
          {
            title: '累计奖励金额：',
            value: 'rewardAllTotal',
            needUnit: true,
            unit: '元'
          }
        ]
      ], //汇总列表
      searchOptions: [
        {
          name: '所属单位',
          valueKey: 'searchQuery',
          type: OrgTreeSelect,
        },
        // {
        //   name: '所属分公司',
        //   type: SelectSubCompany,
        //   valueKey: 'branchCompanyId'
        // },
        // {
        //   name: '所属项目',
        //   type: SelectProject,
        //   valueKey: 'projectId'
        // },
        {
          name: '分包单位',
          valueKey: 'subcontractorId',
          showSearch: true,
          type: SelectSubcontractor
        },
        {
          name: '项目状态',
          type: SelectProjectStatus,
          valueKey: 'projectStatus'
        },
        {
          name: '工匠之星目标类别',
          type: 'select',
          value: 'starCategoryTypeId',
          data: [],
          request: () => typesLabel.getList({ type: '62' })
        },
        {
          name: '获奖人名字',
          value: 'employeeName',
          type: 'input'
        },
        {
          name: '获奖时间',
          value: 'deliverTime',
          type: 'dateRange',
          attr: {
            rangeFormat: ['startDate', 'endDate']
          }
        }
      ],
      columns: [
        // 质量工匠之星表彰卡表头
        [
          {
            title: '序号',
            dataIndex: 'index',
            width: 80
          },
          {
            title: '姓名',
            dataIndex: 'employeeName',
            ellipsis: true
          },
          {
            title: '分包单位',
            dataIndex: 'subcontractorName',
            ellipsis: true
          },
          {
            title: '表彰卡数量',
            dataIndex: 'cardCount',
            ellipsis: true
          },
          {
            title: '表彰卡总额',
            ellipsis: true,
            dataIndex: 'cardTotalValue'
          },
          {
            ellipsis: true,
            title: '分公司',
            dataIndex: 'branchCompanyName'
          },
          {
            title: '所属项目',
            ellipsis: true,
            dataIndex: 'projectName'
          },
          {
            title: ' 操作',
            dataIndex: 'actions',
            width: 180,
            fixed: 'right',
            align: 'center',
            scopedSlots: { customRender: 'actions' }
          }
        ],
        // 月（周）质量工匠之星表头
        [
          {
            title: '序号',
            dataIndex: 'index',
            width: 80
          },
          {
            title: '姓名',
            dataIndex: 'employeeName',
            ellipsis: true
          },
          {
            title: '分包单位',
            dataIndex: 'subcontractorName',
            ellipsis: true
          },
          {
            title: '获奖次数',
            dataIndex: 'rewardCount',
            ellipsis: true
          },
          {
            title: '奖励总额',
            ellipsis: true,
            dataIndex: 'rewardTotalValue'
          },
          {
            ellipsis: true,
            title: '分公司',
            dataIndex: 'branchCompanyName'
          },
          {
            title: '所属项目',
            ellipsis: true,
            dataIndex: 'projectName'
          },
          {
            title: ' 操作',
            dataIndex: 'actions',
            width: 180,
            fixed: 'right',
            align: 'center',
            scopedSlots: { customRender: 'actions' }
          }
        ],
        // 质量工匠之星汇总表头
        [
          {
            title: '序号',
            dataIndex: 'index',
            width: 80
          },
          {
            ellipsis: true,
            title: '分公司',
            dataIndex: 'branchComName'
          },
          {
            title: '项目总数',
            dataIndex: 'projectTotal',
            ellipsis: true
          },
          {
            title: '开展项目数',
            dataIndex: 'developProjectNum',
            ellipsis: true
          },
          {
            title: '推广率',
            dataIndex: 'spread',
            ellipsis: true
          },
          {
            title: '累计发卡数量',
            dataIndex: 'cardNum',
            ellipsis: true
          },
          {
            title: '周质量工匠之星数量',
            dataIndex: 'weekStarNum',
            ellipsis: true
          },
          {
            title: '月质量工匠之星数',
            dataIndex: 'monthStarNum',
            ellipsis: true
          },
          {
            title: '累计奖励金额',
            ellipsis: true,
            dataIndex: 'rewardTotal'
          }
        ]
      ], // 表头
      queryParam: {}, // 表格请求参数
      api: star, // 请求对象
      loadData: (parameter) => {
        if (!this.active) {
          return
        }
        const requestParameters = Object.assign(
          {},
          parameter,
          this.queryParam,
          this.active !== -1 && {
            starType: 1,
            qualityStarTypeId: this.active
          }
        )
        //汇总统计
        this.$nextTick(()=>{
          this.$refs['auditSummary_' + this.active]?.[0]?.getCount()
        })

        let name = this.active === -1 ? 'branchComSummary' : 'postlist'
        return star[name](requestParameters).then((res) => {
          if (this.active === -1 && this.$refs['auditSummary_' + this.active]?.[0]) {
            this.$set(this.$refs['auditSummary_' + this.active][0].countInfo, 'total', res.totalSize)
          }
          res.data?.forEach((i, idx) => {
            i.index = Number(idx) + 1
            i.cardTotalValue && (i.cardTotalValue += '元')
            i.rewardTotalValue && (i.rewardTotalValue += '元')
            i.rewardTotal && (i.rewardTotal += '元')
            i.spread && (i.spread += '%')
          })
          return res
        })
      }
    }
  },
  computed: {
    // 推送月报表头
    columnsTwo() {
      let columns = [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          customRender() {
            return arguments[2] + 1
          }
        },
        {
          title: '发放时间',
          dataIndex: 'createTime'
        },
        {
          title: '发放人',
          dataIndex: 'issuer',
          ellipsis: true
        },
        {
          title: '施工区域',
          dataIndex: 'respArea',
          ellipsis: true
        }
      ]
      if (this.active === '727821124189134526') {
        columns.push(
          {
            title: '表彰卡编号',
            dataIndex: 'cardNum',
            ellipsis: true
          },
          {
            title: '表彰卡面额',
            dataIndex: 'cardValue',
            // customRender(e) {
            //   return e ? e + '元' : ''
            // }
          }
        )
      } else {
        columns.push({
          title: '奖励金额',
          dataIndex: 'rewardValue',
          ellipsis: true,
          customRender(e) {
            return e ? e + '元' : ''
          }
        })
      }
      return [
        ...columns,
        {
          title: '获奖理由',
          dataIndex: 'rewardReasons',
          ellipsis: true
        },
        {
          title: '照片',
          width:150,
          dataIndex: 'fileArrays',
          scopedSlots: { customRender: 'fileArrays' }
        }
      ]
    },
    // 表头当前索引值
    columnIndex() {
      let active = this.tabList?.findIndex((i) => i.id === this.active)
      return active > 0 ? active : 0
    },
    // 导出质量工匠之星文件名称
    exportTitle() {
      return this.tabList.find((i) => i.id === this.active)?.name || '质量工匠之星'
    }
  },
  created() {
    // 获取工匠之星类型
    this.getTypes()
  },
  methods: {
    rowSelection(e) {
      this.countList[this.columnIndex][1].value = e.rows.length
    },
    expandedRowSelection(e) {
      this.countList[3][1].value = e.rows.length
    },
    /**
     * 推送至质量月报
     */
    handlePush() {
      if (!this.$refs.tableDialogForm?.selectedRowKeys?.length) {
        this.$message.warning('请选择需要推送的数据！')
        return
      }
      this.$confirm({
        title: '提示',
        content: '确认推送至质量月报？',
        onOk: () => {
          return star.pushMonth(this.$refs.tableDialogForm.selectedRowKeys).then((res) => {
            if (res.data.code === 200) {
              this.visible = false
              this.$message.success('推送成功！')
              // this.handleSearch() // 刷新列表
            }
          })
        }
      })
    },
    /**
     * 获取工匠之星类型
     */
     getTypes() {
      this.spinning = true
      typesLabel
        .getList({ type:'55' })
        .then((res) => {
          if (res.code === 200) {
              this.active = res.data?.[0].id
              this.tabList = [
                ...res.data,
                {
                  id: -1,
                  name: '质量工匠之星汇总'
                }
              ]
            this.search()
          }
        })
        .finally(() => {
          this.spinning = false
        })
    },
    /**
     * 质量工匠之星汇总详情
     * parameter:分页信息
     * branchCompanyId:分公司id
     */
    getBranchProjectSummary(parameter, branchCompanyId) {
      const requestParameters = Object.assign({}, parameter, { ...this.queryParam }, { branchCompanyId })
      return star.branchProjectSummary(requestParameters).then((res) => {
        return res
      })
    },
    /**
     * 搜索列表
     * val:表单
     */
    search(val) {
      val && (this.queryParam = val)
      this.$refs['table_' + this.active]?.[0]?.refresh(true)
    },
    /**
     * 查看详情
     * data:当前业务对象
     */
    handleOperate(data) {
      const { searchQuery, subcontractorId, ...others } = this.queryParam
      this.$router.push({
        name: 'qualityStarLook', // type：0 安全行为之星；1 质量工匠之星
        query: {
          employeeId: data.employeeId,
          id: data.id,
          type: this.active
        },
        params: others
      })
    }
  }
}
</script>